import uuid

from marshmallow import fields, validate
from sqlalchemy import CHAR, VARCHAR, DateTime, Boolean

from config.database import db
from config.marshmallow_config import ma


class Role(db.Model):
    __tablename__ = 'role'

    id = db.Column(CHAR(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    role_name = db.Column(VARCHAR(50), nullable=False)
    role_value = db.Column(VARCHAR(50), nullable=False)
    status = db.Column(CHAR(1), nullable=False)
    created_at = db.Column(DateTime, nullable=True)
    created_user_id = db.Column(CHAR(36), nullable=True)
    updated_at = db.Column(DateTime, nullable=True)
    updated_user_id = db.Column(CHAR(36), nullable=True)

    def to_dict(self):
        return {
            'id': self.id,
            'roleName': self.role_name,
            'roleValue': self.role_value,
            'status': self.status,
            'createTime': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None,
        }


class RoleSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Role
        load_instance = True

    role_name = fields.String(required=True, validate=validate.Length(min=1, max=50), data_key='roleName')
    role_value = fields.String(required=True, validate=validate.Length(min=1, max=50), data_key='roleValue')
    status = fields.Boolean(required=True)


role_schema = RoleSchema()
roles_schema = RoleSchema(many=True)
